<template>
  <div class="form-comp">
    <div class="toolbar-item toolbar-select"
         v-if="label">
      <el-input size="default"
                :style="{width:(label.length==2?'68px':label.length==3?'82px':label.length==4?'96px':label.length==7?'138px':label.length==6?'128px':''),float:'left'}">
        <template #prepend>{{ label }}</template>
      </el-input>

      <el-select v-model="compValue"
                 placeholder="请选择"
                 size="default"
                 clearable
                 :multiple="multiple"
                 :disabled="disabled"
                 :class="label.length==3?'prepend-3':label.length==4?'prepend-4':label.length==5?'prepend-5':label.length==6?'prepend-6':label.length==7?'prepend-7':'prepend-2'"
      >
        <el-option
            v-for="(item) in compData"
            :key="item.id"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>
    <el-select v-model="compValue"
               :multiple="multiple"
               v-else
               placeholder="请选择"
               size="default"
               clearable
               :disabled="disabled"

               style="width:100%;"
    >
      <el-option
          v-for="(item) in compData"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
  </div>

</template>

<script lang="ts" setup>
//定义组件名称
defineOptions({
  name: "FormDictSelect"
});
// @ts-ignore
import {ref, onMounted, getCurrentInstance, watchEffect, watch} from 'vue'

const props = defineProps({
  label: {type: String, required: false},
  value: {type: Object, required: true},
  dictType: {type: String, required: true},
  disabled: {type: Boolean, required: false},
  multiple: {type: Boolean, required: false, default: false},
});
//组件的值
const compValue = ref<any>(props.value);

const emit = defineEmits(['update:value'])

onMounted(() => {
  loadData();
})

//监听变化
watch(() => props.value, () => {
  if(props.value){
    if (props.multiple) {
      compValue.value = [];
      let values = props.value.split(",");
      for (let i = 0; i < values.length; i++) {
        compValue.value.push(values[i]);
      }
    } else {
      compValue.value = props.value;
    }
  }else{
    compValue.value = "";
  }
})

//监听变化返回
watch(() => compValue.value, () => {
  emit("update:value", compValue.value + "")
}, {
  // deep: true // 可以不写
})
const compData = ref<any>([]);
// @ts-ignore
let {proxy} = getCurrentInstance()

//获取字典列表
function loadData() {
  proxy.$http.post("/user-center/dict/findType", {'dictType': props.dictType}).then((res: any) => {
    compData.value = res.data;
    compValue.value = props.value;
  });
}

</script>

<style scoped>

</style>
